<template>
  <div class="allOrderContainer">
    <div v-if="tabIndex == 0">
      <tobeshipped @valueChanged="(e) => (lobal_list0 = e)"></tobeshipped>
    </div>
    <div v-if="tabIndex == 1">
      <steamcar
        :tabIndexList="tabIndex"
        forceRender
        @valueChanged="(e) => (lobal_list1 = e)"
      ></steamcar>
    </div>
    <div v-if="tabIndex == 2">
      <steamcar
        :tabIndexList="tabIndex"
        forceRender
        @valueChanged="(e) => (lobal_list2 = e)"
      ></steamcar>
    </div>
    <div v-if="tabIndex == 3">
      <steamcar :tabIndexList="tabIndex" forceRender></steamcar>
    </div>
  </div>
</template>

<script>
import {
  TrunklineListFn,
  TrunklineDetailFn,
  TrunklineDepartFn,
  TrunklineArrivalFn,
  TrunklineDepartCancelFn,
  TrunklineLoadCancelFn,
  AbnormalRecordCreate,
} from "@/api/waybill";
import { uploading } from "../material/common/common";
import { reqDictionaryOptions } from "@/api/earlywarning";
import { setToken, getToken } from "@/utils/auth";
import TrunkLine2 from "./components/trunkLine2.vue";
import tobeshipped from "../waybill/tobeshipped.vue";
import steamcar from "../waybill/steamcar/steamcar.vue";
import { reqHandlersList } from "../../api/waybill";
import { dictionanryList } from "../material/common/common";
// import AbnormalDialog from "./components/abnormaldialog.vue"
import StepOperation from "./components/stepOperation.vue";
import { timestamp10 } from "@/utils/mUtils";
import AbnormalModal from "./components/abnormalModal.vue";
import ImportTrunkline from "../../components/waybillPop/ImportTrunkline.vue";

export default {
  name: "trunklinelistpage",
  components: {
    TrunkLine2,
    StepOperation,
    ImportTrunkline,
    tobeshipped,
    steamcar,
  },
  filters: {
    filterStatus(type) {
      const Arr = ["待发车", "已发车", "已到达", "已卸车"];
      return Arr[type];
    },
  },
  data() {
    return {
      lobal_list0: "",
      lobal_list1: "",
      lobal_list2: "",
      orderSearch: {
        departure_time: {}, // 发车时间搜索
        arrival_time: {}, // 到达时间搜索
      },
      pickerOptions: {
        // 时间选择器的快选项
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      orders: [],
      paginations: {
        pageIndex: 1, // 当前位于哪页
        pageSize: 20, // 1页显示多少条
        pageSizes: [10, 20, 50, 100], //每页显示多少条
        total: 200,
        layout: "total, sizes, prev, pager, next, jumper", // 翻页属性
      },
      showDialog: false, // 编辑弹框
      checkIds: [], // 选中id list
      showDepartDialog: false, // 选择发车时间弹框
      departTime: "", // 发车时间
      showArrivalDialog: false, // 选择到达时间弹框
      arrivalTime: "", // 到达时间
      nowId: "", // 当前id,编辑
      ids: [], // id对应的运单id
      thermosphereData: {},
      maxheight: 400,
      drawertrunklineFlagShow: false,
      // tab页的状态管理
      tabIndex: "0",
    };
  },
  mounted() {
    this.getDictionary();
  },
  watch: {
    $route: {
      handler(newV, oldV) {
        if (this.$route.query.type == 0) {
          this.tabIndex = "0";
        } else if (this.$route.query.type == 1) {
          this.tabIndex = "1";
        } else if (this.$route.query.type == 2) {
          this.tabIndex = "2";
        } else if (this.$route.query.type == 3) {
          this.tabIndex = "3";
        }
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {},
  methods: {
    handleWaybillMessage(val) {
      const Fn = ["drawertrunkline"][val];
      this[Fn] && this[Fn]();
      if (val == "2") {
        this.drawertrunkline();
      }
    },
    //干线费用修改
    drawertrunkline() {
      this.drawertrunklineFlagShow = true;
    },
    drawertrunklineFlagShowFn(data) {
      this.drawertrunklineFlagShow = data;
    },
    async handleJump(scope, index) {
      const waybill_id_list = scope.row.waybill_id_list || [];
      const id = waybill_id_list[index];
      let text = this.$router.resolve({
        name: "waybillDetail",
        query: { id, activeName: "1" },
      });
      window.open(text.href, "_blank");
    },
    handleDateChange(name, val) {
      if (val) {
        this.orderSearch[name] = {};
        this.orderSearch[name]["start_time"] = timestamp10(val[0]);
        this.orderSearch[name]["end_time"] = timestamp10(val[1]);
      } else {
        this.orderSearch[name] = {};
      }
    },
    handleSelectionChange(selects) {
      this.checkIds = selects.map((item) => item.id);
      // console.log(this.checkIds);
    },
    getReault(type) {
      let fn, params;
      if (type === "depart") {
        fn = TrunklineDepartFn;
        params = { departure_time: timestamp10(this.departTime) };
      } else if (type === "arrival") {
        fn = TrunklineArrivalFn;
        params = { arrival_time: timestamp10(this.arrivalTime) };
      } else if (type === "cancelDepart") {
        fn = TrunklineDepartCancelFn;
        params = {};
      } else if (type === "cancelLoad") {
        fn = TrunklineLoadCancelFn;
        params = {};
      }
      return new Promise((resolve) => {
        let resultArr = [];
        this.checkIds &&
          this.checkIds.forEach(async (id) => {
            const checked = this.orders.find((item) => item.id === id);
            const res = await fn({
              id,
              ...params,
            });
            if (res.code === 10000) {
              resultArr.push({ ...checked, success: "操作成功" });
            } else {
              resultArr.push({
                ...checked,
                success: "操作失败",
                reason: res.message,
              });
            }
            if (resultArr.length === this.checkIds.length) {
              resolve(resultArr);
            }
          });
      });
    },
    async handleClickDepart() {
      const result = await this.getReault("depart");
      this.alertTable(result, { title: "批量发车" });
      this.showDepartDialog = false;
      this.getTrunklineList();
    },
    alertTable(result, { title }) {
      this.$msgbox({
        title,
        message: (
          <el-table border data={result}>
            <el-table-column
              width="200"
              property="batch"
              label="运输批次"
            ></el-table-column>
            <el-table-column
              width="100"
              property="car_no"
              label="车牌号"
            ></el-table-column>
            <el-table-column
              width="200"
              property="success"
              label="处理状态"
            ></el-table-column>
            <el-table-column
              width="300"
              property="reason"
              label="失败原因"
            ></el-table-column>
          </el-table>
        ),
        customClass: "temperature_msg",
        showConfirmButton: true,
        showCancelButton: false,
        confirmButtonText: "关闭",
      });
    },
    async handleClickArrival() {
      const result = await this.getReault("arrival");
      this.alertTable(result, { title: "批量到达" });
      this.showArrivalDialog = false;
      this.getTrunklineList();
    },
    handleClickEdit({ id, waybill_id_list = [] }) {
      this.nowId = id;
      this.ids = waybill_id_list.map(Number);
      this.showDialog = true;
    },
    handleSearch() {
      this.paginations.pageIndex = 1;
      this.getTrunklineList();
    },
    handleReset() {
      this.orderSearch = {};
      this.paginations.pageIndex = 1;
      this.getTrunklineList();
    },
    handleClickOperation(type) {
      if (this.checkIds.length === 0) {
        this.$message({
          message: "请选中后进行操作",
          type: "warning",
        });
        return;
      }
      if (type === 1) {
        this.departTime = Date.now();
        this.showDepartDialog = true;
      } else if (type === 2) {
        this.arrivalTime = Date.now();
        this.showArrivalDialog = true;
      } else if (type === 3) {
        this.$alert("确定要取消发车吗？", "提示", {
          confirmButtonText: "确定",
          callback: async (action) => {
            // console.log(action, "action");
            if (action === "confirm") {
              const result = await this.getReault("cancelDepart");
              this.alertTable(result, { title: "取消发车" });
              this.getTrunklineList();
            }
          },
        });
      } else if (type === 4) {
        this.$alert("确定要删除运输单吗？", "提示", {
          confirmButtonText: "确定",
          callback: async (action) => {
            if (action === "confirm") {
              const result = await this.getReault("cancelLoad");
              this.alertTable(result, { title: "取消装车" });
              this.getTrunklineList();
            }
          },
        });
      }
    },
    handleCloseDialog(isUpdate = true) {
      this.showDialog = false;
      isUpdate && this.getTrunklineList();
    },
    getTrunklineList() {
      TrunklineListFn({
        ...this.orderSearch,
        page: this.paginations.pageIndex,
        page_size: this.paginations.pageSize,
      }).then((res) => {
        const list = res.data.list || [];
        list.forEach((item) => {
          item.waybill_id_list = item.dispatch_waybills.map(
            (w) => w.waybill_id
          );
          item.waybill_no_list = item.dispatch_waybills.map(
            (w) => w.waybill_no
          );
        });
        this.orders = [...list];
        this.paginations.total = res.data.total;
      });
    },
    //异常操作
    clickabnormalFn(valData) {
      const { dispatch_waybills = [], id } = valData;
      const waybill_id_list = dispatch_waybills.map((item) => item.waybill_id);
      this.$msgbox({
        title: "提交异常",
        message: (
          <AbnormalModal
            key={Math.random()}
            step={2}
            waybillIds={waybill_id_list}
            nodeId={id}
            style="width:600px"
          ></AbnormalModal>
        ),
        customClass: "temperature_msg",
        showConfirmButton: false,
        showCancelButton: false,
        closeOnClickModal: false,
        showClose: true,
      });
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.paginations.pageSize = val;
      this.getTrunklineList();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.paginations.pageIndex = val;
      this.getTrunklineList();
    },
    getDictionary() {
      dictionanryList(["thermosphere"]).then((res) => {
        const data = res.data.list["thermosphere"];
        data.forEach((item) => {
          const { item_code, item_name } = item;
          this.thermosphereData[item_code] = item_name;
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
// /deep/ .el-tabs__nav-wrap {
//   left: -183px !important;
// }
// /deep/.badge_item .el-badge__content {
//   height: 15px;
//   line-height: 15px;
// }

// /deep/.badge_item .el-badge__content.is-fixed {
//   top: 6px;
// }
/deep/.el-tabs--border-card .el-tabs__content {
  // height: 15px;
  line-height: 15px;
  padding: 0px;
}

/deep/.badge_item .el-badge__content.is-fixed {
  top: 8px;
}

// /deep/.el-badge__content.is-fixed {
//   transform: translateY(-3%) translateX(100%);
// }
.allOrderContainer {
  padding: 10px 15px;
  background-color: #fff;
  ::v-deep .el-tabs--border-card {
    -webkit-box-shadow: none;
    border: none;
  }
  .orderHeader {
    margin-top: 5px;
    background-color: #fff;

    .orderSearch {
      form {
        ::v-deep .el-form-item__label {
          font-size: 12px;
        }

        .el-textarea {
          width: 135px;
        }
      }
    }
  }

  .actions {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    width: 100%;
    background-color: #fff;
    padding: 0px 15px 0px 0px;
  }
}
</style>
<style>
.temperature_msg {
  width: auto;
}
</style>